<?php
/**
 * Created by PhpStorm.
 * User: wuchunyin
 * Date: 2018/11/8
 * Time: 13:36
 */

namespace app\index\controller;
use app\index\base_controller\BaseController;
use app\index\table\ArchiveBaseTable;
use app\index\table\ArchiveBookTable;
use app\index\table\ArchiveBuildingTable;
use app\index\table\ArchiveFacilityTable;
use app\index\table\ArchiveFurnTable;
use app\index\table\ArchiveLandTable;
use app\index\table\ArchiveLogTable;
use app\index\table\BookAlterTable;
use app\index\table\BookTable;
use app\index\table\BuildingTable;
use app\index\table\FacilityAlterTable;
use app\index\table\FacilityTable;
use app\index\table\FurnAlterTable;
use app\index\table\FurnTable;
use app\index\table\LandTable;
use think\Db;
use think\Exception;

class Archive extends BaseController{

    public function archiveTest(){
        $d1 = ArchiveFurnTable::table()->find();
        dump($d1);

    }

    /**
     * page--归档
     */
    public function archivePage(){
        return view('archive');
    }

    /**
     * action 获取归档记录
     */
    public function getLogList(){
        $limit = input('limit');
        $offset = input('offset');
        $sort = input('sort');
        $search = input('search');
        $order = input('order');
        $sortStr = "$sort $order";
        if(empty($sort)){
            $sortStr = 'LOG_ID desc';
        }

        $condition = null;
        if(!empty($search)){
            $condition[] = ['YEARMONTH|USER_NAME','like',"$search"];
        }

        try{
            $list = ArchiveLogTable::table()->where($condition)->order($sortStr)->limit($offset,$limit)->select();
            $total = ArchiveLogTable::table()->where($condition)->count();
            return ['rows'=>$list,'total'=>$total];
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

    /**
     * action 执行归档操作
     */
    public function doArchive(){
        $yearmonth = input('yearmonth');
        if(!preg_match('/[0-9]{4}-[0-9]{2}/',$yearmonth)){
            return json_encode(['code'=>'0','msg'=>'请输入正确的归档年月，如:2018-10']);
        }
        if(strtotime($yearmonth) === false){
            return json_encode(['code'=>'0','msg'=>'请输入正确的归档年月，如:2018-10']);
        }

        try{
            Db::startTrans();
            $this->archiveFacility($yearmonth);
            $this->archiveBook($yearmonth);
            $this->archiveLand($yearmonth);
            $this->archiveBuilding($yearmonth);
            $this->archiveFurn($yearmonth);
            ArchiveLogTable::add(['YEARMONTH'=>$yearmonth]);
            Db::commit();
            return json_encode(['code'=>'200','msg'=>'归档成功']);
        }
        catch (Exception $e){
            Db::rollback();
            return json_encode(['code'=>'0','msg'=>'操作失败:'.$e->getMessage()]);
        }
    }

    /**
     * 归档设备
     */
    public function archiveFacility($yearmonth){

        $firstday = date('Y-m-01', strtotime($yearmonth));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));

        $facilityList = FacilityTable::table()->where([['ENTERTIME','<=',$lastday]])->select();
        if(!empty($facilityList)){
            foreach ($facilityList as $item){
                $facilityNo = $item['FACILITY_NO'];
                $alterList = FacilityAlterTable::table()
                    ->where("FACILITY_NO='$facilityNo' AND ALTER_DATE>'$lastday'")
                    ->order('RECEIPT_NO DESC')
                    ->select();

                if(!empty($alterList)){
                    for($i = 0 ; $i < count($alterList) ; $i++){
                        $alter = $alterList[$i];
                        if($alter['ALTERTYPE_ID'] == '99'){
                            $item['STATE_ID'] = '1';
                        }
                        if($alter['ALTERTYPE_ID'] == '02'){
                            $item['PRICE'] = $alter['PRICE_BEF'];
                        }
                    }
                }

                unset($item['FACITYPE']);
                unset($item['COLLEGE_ID']);
                unset($item['COLLEGE']);
                unset($item['BELONG_DEPART_NAME']);
                unset($item['USE_DEPART_NAME']);
                unset($item['COUNTRY_CNNAME']);
                unset($item['USEDIRECTION']);
                unset($item['FININ']);
                unset($item['STATE']);
                unset($item['ASSET_TYPE']);
                unset($item['BELONG']);
                unset($item['NUMROW']);
                $item['ARCHIVE_YEARMONTH'] = $yearmonth;
                ArchiveFacilityTable::insert($item);
            }
        }

        $priceInterval = [
            ['NAME'=>'小于10万','WHERE'=>'PRICE<100000']
            ,['NAME'=>'10万-40万（含10万）','WHERE'=>'PRICE>=100000 AND PRICE<400000']
            ,['NAME'=>'40万-100万（含40万）','WHERE'=>'PRICE>=400000 AND PRICE<1000000']
            ,['NAME'=>'100万-200万（含100万）','WHERE'=>'PRICE>=1000000 AND PRICE<2000000']
            ,['NAME'=>'200万以上（含200万）','WHERE'=>'PRICE>=2000000']
        ];

        foreach ($priceInterval as $item){
            $data = ArchiveFacilityTable::table()
                ->field("BELONG,COLLEGE,COUNT(*) AS ASSET_NUM,SUM(PRICE) AS ASSET_PRICE")
                ->where(['ARCHIVE_YEARMONTH'=>$yearmonth,'STATE_ID'=>'1'])
                ->where($item['WHERE'])
                ->group("BELONG,COLLEGE")
                ->find();

            if(!empty($data)){
                $ret = ArchiveBaseTable::insert([
                    'BELONG_NAME'=>$data['BELONG']
                    ,'TYPE_NAME'=>'设备'
                    ,'COLLEGE_NAME'=>$data['COLLEGE']
                    ,'PRICE_INTERVAL'=>$item['NAME']
                    ,'YEARMONTH'=>$yearmonth
                    ,'ASSET_NUM'=>$data['ASSET_NUM']
                    ,'ASSET_PRICE'=>$data['ASSET_PRICE']
                    ,'ASSET_SIZE'=>0
                ]);
            }
        }
    }

    /**
     * 归档图书
     */
    public function archiveBook($yearmonth){

        $firstday = date('Y-m-01', strtotime($yearmonth));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));

        $bookList = BookTable::table()->where([['ENTER_DATE','<=',$lastday]])->select();
        if(!empty($bookList)){
            foreach ($bookList as $item){
                $bookNo = $item['BOOK_NO'];
                $alterList = BookAlterTable::table()
                    ->where("BOOK_NO='$bookNo' AND ALTER_DATE>'$lastday'")
                    ->order('ALTER_NO DESC')
                    ->select();

                if(!empty($alterList)){
                    for($i = 0 ; $i < count($alterList) ; $i++){
                        $alter = $alterList[$i];
                        if($alter['ALTERTYPE_ID'] == '57'){//报废
                            $item['BOOK_NUM'] += $alter['ALTER_NUM'];
                            $item['BOOK_FEE'] += $alter['ALTER_VALUE'];
                        }
                    }
                }

                unset($item['ASSET_TYPE']);
                unset($item['PURCHASE']);
                unset($item['GETTYPE']);
                unset($item['ENTER_TYPE']);
                unset($item['VALUETYPE']);
                unset($item['STATUS']);
                unset($item['USEDIRECTION']);
                unset($item['USE_COLLEGE']);
                unset($item['MGR_COLLEGE']);
                unset($item['DEPRECIATE']);
                unset($item['INPUT_NAME']);
                unset($item['BELONG']);
                unset($item['NUMROW']);
                $item['ARCHIVE_YEARMONTH'] = $yearmonth;
                ArchiveBookTable::insert($item);
            }
        }

        $data = ArchiveBookTable::table()
            ->field("BELONG,COLLEGE,SUM(BOOK_NUM) AS ASSET_NUM,SUM(BOOK_FEE) AS ASSET_PRICE")
            ->where(['ARCHIVE_YEARMONTH'=>$yearmonth])
            ->group("BELONG,COLLEGE")
            ->find();

        if(!empty($data)){
            $ret = ArchiveBaseTable::insert([
                'BELONG_NAME'=>$data['BELONG']
                ,'TYPE_NAME'=>'图书'
                ,'COLLEGE_NAME'=>$data['COLLEGE']
                ,'PRICE_INTERVAL'=>'图书'
                ,'YEARMONTH'=>$yearmonth
                ,'ASSET_NUM'=>$data['ASSET_NUM']
                ,'ASSET_PRICE'=>$data['ASSET_PRICE']
                ,'ASSET_SIZE'=>0
            ]);
        }
    }

    /**
     * 归档家具
     */
    public function archiveFurn($yearmonth){
        $firstday = date('Y-m-01', strtotime($yearmonth));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));

        $furnList = FurnTable::table()->where("to_char(ENTER_TIME,'yyyy-mm-dd') <= '$lastday'")->select();
        if(!empty($furnList)){
            foreach ($furnList as $item){
                $furnNo = $item['FURN_NO'];
                $alterList = FurnAlterTable::table()
                    ->where("fa.FURN_NO='$furnNo' AND to_char(ALTER_TIME,'yyyy-mm-dd')>'$lastday'")
                    ->order('ALTER_NO DESC')
                    ->select();

                if(!empty($alterList)){
                    for($i = 0 ; $i < count($alterList) ; $i++){
                        $alter = $alterList[$i];
                        if($alter['ALTERTYPE_ID'] == '02'){//报废
                            $item['STATE_ID'] = '01';
                        }
                        if($alter['ALTERTYPE_ID'] == '01'){//调拨
                            $item['DEPART_ID'] = $alter['DEPARTNEW_ID'];
                        }
                    }
                }

                unset($item['FACITYPE']);
                unset($item['DEPART_SHORT']);
                unset($item['COLLEGE_ID']);
                unset($item['SHORTNAME']);
                unset($item['COUNTRY_CNNAME']);
                unset($item['STATE']);
                unset($item['INPUT_NAME']);
                unset($item['GB_NAME']);
                unset($item['ZIJIN']);
                unset($item['BELONG']);
                unset($item['ASSET_TYPE']);
                unset($item['BELONG']);
                unset($item['NUMROW']);
                $item['ARCHIVE_YEARMONTH'] = $yearmonth;
                ArchiveFurnTable::insert($item);
            }
        }



        $data = ArchiveFurnTable::table()
            ->field("BELONG,COLLEGE,COUNT(*) AS ASSET_NUM,SUM(PRICE) AS ASSET_PRICE")
            ->where(['ARCHIVE_YEARMONTH'=>$yearmonth])
            ->group("BELONG,COLLEGE")
            ->find();

        if(!empty($data)){
            $ret = ArchiveBaseTable::insert([
                'BELONG_NAME'=>$data['BELONG']
                ,'TYPE_NAME'=>'家具'
                ,'COLLEGE_NAME'=>$data['COLLEGE']
                ,'PRICE_INTERVAL'=>'家具'
                ,'YEARMONTH'=>$yearmonth
                ,'ASSET_NUM'=>$data['ASSET_NUM']
                ,'ASSET_PRICE'=>$data['ASSET_PRICE']
                ,'ASSET_SIZE'=>0
            ]);
        }
    }

    /**
     * 归档土地
     */
    public function archiveLand($yearmonth){

        $firstday = date('Y-m-01', strtotime($yearmonth));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));

        $landList = LandTable::table()->select();
        if(!empty($landList)){
            foreach ($landList as $item){
                unset($item['ASSET_TYPE']);
                unset($item['PROPERTYRIGHT']);
                unset($item['POWERTYPE']);
                unset($item['VALUETYPE']);
                unset($item['GETTYPE']);
                unset($item['PURCHASE']);
                unset($item['STATUS']);
                unset($item['COLLEGE']);
                unset($item['INPUT_NAME']);
                unset($item['NUMROW']);
                $item['ARCHIVE_YEARMONTH'] = $yearmonth;
                ArchiveLandTable::insert($item);
            }
        }

        $data = ArchiveLandTable::table()
            ->field("COUNT(*) AS ASSET_NUM,SUM(LAND_FEE) AS ASSET_PRICE,SUM(LAND_SIZE) AS ASSET_SIZE")
            ->where(['ARCHIVE_YEARMONTH'=>$yearmonth])
            ->find();

        if(!empty($data)){
            $ret = ArchiveBaseTable::insert([
                'BELONG_NAME'=>'天津大学'
                ,'TYPE_NAME'=>'土地'
                ,'COLLEGE_NAME'=>'天津大学'
                ,'PRICE_INTERVAL'=>'土地'
                ,'YEARMONTH'=>$yearmonth
                ,'ASSET_NUM'=>$data['ASSET_NUM']
                ,'ASSET_PRICE'=>$data['ASSET_PRICE']
                ,'ASSET_SIZE'=>$data['ASSET_SIZE']
            ]);
        }
    }

    /**
     * 归档建筑
     */
    public function archiveBuilding($yearmonth){

        $firstday = date('Y-m-01', strtotime($yearmonth));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));

        $buildingList = BuildingTable::table()->where([['ENTER_DATE','<=',$lastday]])->select();
        if(!empty($buildingList)){
            foreach ($buildingList as $item){
                unset($item['ASSET_TYPE']);
                unset($item['PROPERTYRIGHT']);
                unset($item['GETTYPE']);
                unset($item['POWERTYPE']);
                unset($item['CONSTRU']);
                unset($item['ENTER_TYPE']);
                unset($item['USEDIRECTION']);
                unset($item['STATUS']);
                unset($item['COLLEGE']);
                unset($item['VALUETYPE']);
                unset($item['DEPRECIATE']);
                unset($item['INPUT_NAME']);
                unset($item['NUMROW']);
                $item['ARCHIVE_YEARMONTH'] = $yearmonth;
                ArchiveBuildingTable::insert($item);
            }
        }

        $data = ArchiveBuildingTable::table()
            ->field("COUNT(*) AS ASSET_NUM,SUM(BUILDING_FEE) AS ASSET_PRICE,SUM(BUILD_SIZE) AS ASSET_SIZE")
            ->where(['ARCHIVE_YEARMONTH'=>$yearmonth])
            ->find();

        if(!empty($data)){
            $ret = ArchiveBaseTable::insert([
                'BELONG_NAME'=>'天津大学'
                ,'TYPE_NAME'=>'建筑'
                ,'COLLEGE_NAME'=>'天津大学'
                ,'PRICE_INTERVAL'=>'建筑'
                ,'YEARMONTH'=>$yearmonth
                ,'ASSET_NUM'=>$data['ASSET_NUM']
                ,'ASSET_PRICE'=>$data['ASSET_PRICE']
                ,'ASSET_SIZE'=>$data['ASSET_SIZE']
            ]);
        }
    }

}
































































